package com.unis.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.unis.common.util.TemplateUtil;
import com.unis.dto.ResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.service.impl.BaseServiceImpl;
import com.unis.mapper.system.MenuMapper;
import com.unis.model.system.Menu;
import com.unis.service.system.MenuService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see MenuService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-01-07
 */
@Service("menuService")
public class MenuServiceImpl extends BaseServiceImpl implements MenuService {
	private static final Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);
    @Autowired
    private MenuMapper menuMapper;

    /**
     * @see MenuService#insert(Menu menu)
     */
    @Override
    public int insert(Menu menu) throws Exception {
    	if (menu!=null){
	        menu.setPk(TemplateUtil.genUUID());
			//menu.setPk(getPk("seqName","jgdm","MU"));
	        return menuMapper.insertSelective(menu);
    	}else{
    		logger.error("MenuServiceImpl.insert时menu数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.insert时menu数据为空。");
    	}        
    }

    /**
     * @see MenuService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("MenuServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("MenuServiceImpl.delete时pk为空。");
    	}else{
    		return menuMapper.deleteByPrimaryKey(pk);
    	}
    }

    /**
     * @see MenuService#updateByPrimaryKey(Menu menu)
     */
    @Override
    public int updateByPrimaryKey(Menu menu) throws Exception {
        if (menu!=null){
        	if(StringUtils.isBlank(menu.getPk())){
        		logger.error("MenuServiceImpl.updateByPrimaryKey时menu.Pk为空。");
        		throw new AppRuntimeException("MenuServiceImpl.updateByPrimaryKey时menu.Pk为空。");
        	}
	        return menuMapper.updateByPrimaryKeySelective(menu);
    	}else{
    		logger.error("MenuServiceImpl.updateByPrimaryKey时menu数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.updateByPrimaryKey时menu数据为空。");
    	}
    }
    /**
     * @see MenuService#queryMenuByPrimaryKey(String pk)
     */
    @Override
    public Menu queryMenuByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("MenuServiceImpl.queryMenuByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("MenuServiceImpl.queryMenuByPrimaryKey时pk为空。");
    	}else{
    		return menuMapper.selectByPrimaryKey(pk);
    	}
    }
    
    
    /**
     * @see MenuService#queryAsObject(Menu menu)
     */
    @Override
    public Menu queryAsObject(Menu menu) throws Exception {
        if (menu!=null){
	        return menuMapper.selectOne(menu);
    	}else{
    		logger.error("MenuServiceImpl.queryAsObject时menu数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.queryAsObject时menu数据为空。");
    	}
    }
    
    /**
     * @see MenuService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return menuMapper.selectCountByExample(example);
    	}else{
    		logger.error("MenuServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see MenuService#queryListByExample(Example example)
     */
    @Override
    public List<Menu> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return menuMapper.selectByExample(example);
    	}else{
    		logger.error("MenuServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see MenuService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(menuMapper.selectByExample(example));
    	}else{
    		logger.error("MenuServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("MenuServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }

	@Override
	public List<Map<String, Object>> queryMenuAll() throws Exception {
		List<Map<String, Object>> oneMenuList = null;
		List<Map<String, Object>> twoMenuList = null;
		List<Map<String, Object>> threeMenuList = null;

		int codeLevel = 1;
		String parentCode = null;
		String userId = getUserInfo().getPk();
		//一级
		oneMenuList = this.queryMenuByParm(userId,codeLevel,parentCode);

		if (oneMenuList!=null && oneMenuList.size()>0){
			for (Map<String,Object> oneMap : oneMenuList){
				if(oneMap!=null && oneMap.get("isparent")!=null && (Short)oneMap.get("isparent") == 1){
					twoMenuList = this.queryMenuByParm(userId,(Short)oneMap.get("level")+1,oneMap.get("code").toString());
					oneMap.put("cld",twoMenuList);

					if (twoMenuList!=null && twoMenuList.size()>0){
						for (Map<String,Object> twoMap : twoMenuList){
							if(twoMap!=null && twoMap.get("isparent")!=null && (Short)twoMap.get("isparent") == 1){
								threeMenuList = this.queryMenuByParm(userId,(Short)twoMap.get("level")+1,twoMap.get("code").toString());
								twoMap.put("cld",threeMenuList);
								threeMenuList = null;
							}
						}
					}
					twoMenuList = null;
				}
			}
		}


		return oneMenuList;
	}
	@Override
	public List<Map<String, Object>> queryMenuByParm(String userId,int codeLevel,String parentCode)  {
		List<Map<String, Object>> list = null;
		List<Menu> menuList = null;

		menuList = menuMapper.selectPermissionMenuByLevel(userId,codeLevel,parentCode);

		if (menuList!=null && menuList.size()>0){
			list = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (Menu menu : menuList){
				map = new HashMap<String, Object>();
				map.put("name",menu.getName());
				map.put("icon",menu.getIcon());
				map.put("isparent",menu.getIsparent());
				map.put("pageId",menu.getPageId());
				map.put("url",menu.getUrl());
				map.put("code",menu.getCode());
				map.put("level",menu.getCodeLevel());
				list.add(map);
			}
		}
    	return list;
	}
	/**
	 * @see MenuService#queryListByPage(Map parmMap,int pageNum,int pageSize)
	 */
	@Override
	public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
		if (parmMap!=null){
			Example example = new Example(Menu.class);
			example.setOrderByClause("px asc");//设置排序
			Example.Criteria criteria = example.createCriteria();
			//criteria设置
			// = --> andEqualTo(field,value)
			// like --> andLike(field,likeValue)；likeValue 包含‘%’
			// is null --> andIsNull(field)
			// is not null --> andIsNotNull(field)
			// <> --> andNotEqualTo(field)
			// > --> andGreaterThan(field,value)
			// >= --> andGreaterThanOrEqualTo(field,value)
			// < --> andLessThan(field,value)
			// <= --> andLessThanOrEqualTo(field,value)
			// in --> andIn(field,Iterable value)
			// not in --> andNotIn(field,Iterable value)
			// between --> andBetween(field,beginValue,endValue)
			// not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

			// or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

			criteria.andEqualTo("yxx",1);//设置yxx=1
			/**
			 *此方法请根据需要修改下方条件
			 */
			//此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
			//生成条件中均为 and field = value
			//生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改
			if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
			}
			if(parmMap.get("code")!=null && StringUtils.isNotBlank(parmMap.get("code").toString())){
				criteria.andEqualTo("code",parmMap.get("code").toString().trim());
			}
			if(parmMap.get("name")!=null && StringUtils.isNotBlank(parmMap.get("name").toString())){
				criteria.andEqualTo("name",parmMap.get("name").toString().trim());
			}
			/*if(parmMap.get("icon")!=null && StringUtils.isNotBlank(parmMap.get("icon").toString())){
				criteria.andEqualTo("icon",parmMap.get("icon").toString().trim());
			}*/
			if(parmMap.get("pageId")!=null && StringUtils.isNotBlank(parmMap.get("pageId").toString())){
				criteria.andEqualTo("pageId",parmMap.get("pageId").toString().trim());
			}
			if(parmMap.get("isparent")!=null && StringUtils.isNotBlank(parmMap.get("isparent").toString())){
				criteria.andEqualTo("isparent",parmMap.get("isparent").toString().trim());
			}
			if(parmMap.get("url")!=null && StringUtils.isNotBlank(parmMap.get("url").toString())){
				criteria.andLike("url","%"+parmMap.get("url").toString().trim()+"%");
			}
			if(parmMap.get("parentCode")!=null && StringUtils.isNotBlank(parmMap.get("parentCode").toString())){
				criteria.andEqualTo("parentCode",parmMap.get("parentCode").toString().trim());
			}
			if(parmMap.get("codeLevel")!=null && StringUtils.isNotBlank(parmMap.get("codeLevel").toString())){
				criteria.andEqualTo("codeLevel",parmMap.get("codeLevel").toString().trim());
			}
			/*if(parmMap.get("cType")!=null && StringUtils.isNotBlank(parmMap.get("cType").toString())){
				criteria.andEqualTo("cType",parmMap.get("cType").toString().trim());
			}*/
			if(parmMap.get("comments")!=null && StringUtils.isNotBlank(parmMap.get("comments").toString())){
				criteria.andEqualTo("comments",parmMap.get("comments").toString().trim());
			}
			PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			result.setTotal((int)pageInfo.getTotal());
			return result;
		}else{
			logger.error("MenuServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("MenuServiceImpl.queryListByPage时parmMap数据为空。");
		}
	}

}
